package com.dtw.ditouwang.ui.movement;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.weather.LocalWeatherForecastResult;
import com.amap.api.services.weather.LocalWeatherLiveResult;
import com.amap.api.services.weather.WeatherSearch;
import com.amap.api.services.weather.WeatherSearchQuery;
import com.dtw.ditouwang.R;
import com.dtw.ditouwang.beans.ChallengeListBean;
import com.dtw.ditouwang.beans.MovementBackBean;
import com.dtw.ditouwang.beans.MovementUpdateBean;
import com.dtw.ditouwang.repositories.UserRepository;
import com.dtw.ditouwang.ui.BaseActivity;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MovementInsideActivity extends BaseActivity implements View.OnClickListener, SensorEventListener {

    private TextView textDistance;
    private TextView textTime;
    private TextView textSpeed;
    private TextView testSpeed2;
    private TextView textCalorie;
    private Button textContinue;
    private Button textStop;
    private LinearLayout viewPaused;
    ImageView countdownImg;
    private Button textPause;
    private LinearLayout viewStarted;
    SensorManager sensorManager;
    Sensor sensor;
    int startStep = -1, step = 0;
    int stepLength = 50;
    Timer timer;
    int movementTime = 0;
    private ChallengeListBean.DataBean challengeBean;
    AMapLocationClient aMapLocationClient;
    String weather="晴";
    String walk="健走";
    List<MovementUpdateBean.SubsectionBean.ValueBean> avgEveryMintus = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
        }
        setContentView(R.layout.activity_movement_inside);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(Color.BLACK);
        }
        initView();
        challengeBean = getIntent().getParcelableExtra(MovementChallengeActivity.KeyChallengeBean);
        if(!challengeBean.isWalk()){
            walk="跑步";
        }
        setTitle("室内"+walk);
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        stepLength = new Random().nextInt(20) + 45;
        getWeather();

        new CountDownTimer(3100, 1000) {

            @Override
            public void onTick(long l) {
                if (l < 2000) {
                    countdownImg.setImageResource(R.drawable.pic_1);
                }else if (l < 3000) {
                    countdownImg.setImageResource(R.drawable.pic_2);
                }
            }

            @Override
            public void onFinish() {
                countdownImg.setVisibility(View.GONE);
                startMovement();
            }
        }.start();
    }

    private void initView() {
        textDistance = findViewById(R.id.text_distance);
        textTime = findViewById(R.id.text_time);
        textSpeed = findViewById(R.id.text_speed);
        testSpeed2 = findViewById(R.id.test_speed_2);
        textCalorie = findViewById(R.id.text_calorie);
        textContinue = findViewById(R.id.text_continue);
        textContinue.setOnClickListener(this);
        textStop = findViewById(R.id.text_stop);
        textStop.setOnClickListener(this);
        viewPaused = findViewById(R.id.view_paused);
        textPause = findViewById(R.id.text_pause);
        textPause.setOnClickListener(this);
        viewStarted = findViewById(R.id.view_started);
        countdownImg = findViewById(R.id.img_coundown);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.text_continue:
                viewStarted.setVisibility(View.VISIBLE);
                viewPaused.setVisibility(View.INVISIBLE);
                startMovement();
                break;
            case R.id.text_stop:
                if(step==0){
                    showToast("运动距离太短，无法保存");
                    return;
                }
                textStop.setClickable(false);
                stopMovement();
                MovementUpdateBean movementUpdateBean = new MovementUpdateBean();
                movementUpdateBean.setId(UserRepository.getInstance().getUserID());
                movementUpdateBean.setAvg_speed(step * stepLength / 100f / 1000f / (movementTime / 60f));
                movementUpdateBean.setChallenge_id(challengeBean.getId());
                movementUpdateBean.setIs_challenge(challengeBean.isChallenge() ? 1 : 0);
                movementUpdateBean.setMileage(String.format("%.2f",step * stepLength / 100f / 1000f));
                movementUpdateBean.setQuantity(60 * movementTime / 60f / 60f * 30 / (movementTime / 60f / (step * stepLength / 100f / 1000f) / 1000f * 400));
                movementUpdateBean.setRoom_type(1);
                movementUpdateBean.setSpeed_distribution((movementTime / ((step==0?1:step) * stepLength / 100f / 1000f)));
                movementUpdateBean.setStep(step);
                movementUpdateBean.setStep_frequency(step / (movementTime / 60f));
                movementUpdateBean.setStride(stepLength);
                movementUpdateBean.setTime(movementTime);
                movementUpdateBean.setType(challengeBean.isWalk() ? 1 : 2);
                movementUpdateBean.setWeather(weather);
                movementUpdateBean.setTrajectory(null);
                MovementUpdateBean.SubsectionBean subsectionBean=new MovementUpdateBean.SubsectionBean();
                subsectionBean.setMovementTime((int)movementTime/60);
                subsectionBean.setValues(avgEveryMintus);
                movementUpdateBean.setSubsection(subsectionBean);
                webApi.upLoadMovement(new Gson().toJson(movementUpdateBean)).enqueue(new Callback<MovementBackBean>() {
                    @Override
                    public void onResponse(Call<MovementBackBean> call, Response<MovementBackBean> response) {
                        if(response.body().isResult()){
                            Intent intent=new Intent(MovementInsideActivity.this,MovementOverActivity.class);
                            intent.putExtra(MovementOverActivity.KeyMoovementOverData, response.body().getData());
                            startActivity(intent);
                            finish();
                        }
                    }

                    @Override
                    public void onFailure(Call<MovementBackBean> call, Throwable t) {
                        Log.i("dtw", t.getMessage());
                    }
                });
                break;
            case R.id.text_pause:
                stopMovement();
                viewStarted.setVisibility(View.INVISIBLE);
                viewPaused.setVisibility(View.VISIBLE);
                break;
        }
    }

    public void startMovement() {
        recordTime();
        if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_SENSOR_STEP_COUNTER)) {
            sensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
            sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_UI);
        } else if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_SENSOR_STEP_DETECTOR)) {
            sensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
            sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_UI);
        }
    }

    public void stopMovement() {
        stopTime();
        sensorManager.unregisterListener(this);
    }

    float lastMinutesDistance =0;
    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
            if (startStep == -1) {
                startStep = (int) event.values[0];
            }
            step = (int) event.values[0] - startStep;
        } else if (event.sensor.getType() == Sensor.TYPE_STEP_DETECTOR) {
            step += (int) event.values[0];
        }
        Log.i("dtw", "time:" + movementTime + "step:" + step);
        if (step != 0) {
            textSpeed.setText(String.format("%.0f′%02.0f″ ", (float) (int) (movementTime / (step * stepLength / 100f / 1000f)) / 60,
                    ((movementTime / (step * stepLength / 100f / 1000f))) % 60));
            testSpeed2.setText(String.format("%.2f", step * stepLength / 100f / 1000f / (movementTime / 60f)));
            textCalorie.setText(String.format("%.0f ", 60 * movementTime / 60f / 60f * 30 / (movementTime / 60f / (step * stepLength / 100f / 1000f) / 1000f * 400)));
            textDistance.setText(String.format("%.2f", step * stepLength / 100f / 1000f));
        }
        Log.i("dtw", event.values[0] + "");
        if(movementTime%60==0){
            MovementUpdateBean.SubsectionBean.ValueBean avg=new MovementUpdateBean.SubsectionBean.ValueBean();
            avg.setValue((step * stepLength / 100f / 1000f- lastMinutesDistance)/(1f/60));
            avgEveryMintus.add(avg);
            lastMinutesDistance =step * stepLength / 100f / 1000f;
        }
    }

    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(this).setMessage("当前数据尚未保存，是否离开").setPositiveButton("留下", null)
                .setNegativeButton("留下", null)
                .setPositiveButton("离开", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        MovementInsideActivity.super.onBackPressed();
                    }
                }).show();
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    public void getWeather() {
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
        mLocationOption.setOnceLocation(true);
        aMapLocationClient = new AMapLocationClient(this);
        aMapLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                WeatherSearchQuery mquery = new WeatherSearchQuery(aMapLocation.getCity(), WeatherSearchQuery.WEATHER_TYPE_LIVE);
                WeatherSearch mweathersearch=new WeatherSearch(MovementInsideActivity.this);
                mweathersearch.setOnWeatherSearchListener(new WeatherSearch.OnWeatherSearchListener() {
                    @Override
                    public void onWeatherLiveSearched(LocalWeatherLiveResult localWeatherLiveResult, int i) {
                        weather = localWeatherLiveResult.getLiveResult().getWeather();
                        Log.i("dtw", "weather：" + localWeatherLiveResult.getLiveResult().getCity() + localWeatherLiveResult.getLiveResult().getWeather());
                    }

                    @Override
                    public void onWeatherForecastSearched(LocalWeatherForecastResult localWeatherForecastResult, int i) {

                    }
                });
                mweathersearch.setQuery(mquery);
                mweathersearch.searchWeatherAsyn(); //异步搜索
            }
        });
        aMapLocationClient.startLocation();
    }

    @Override
    protected void onDestroy() {
        stopMovement();
        super.onDestroy();
    }

    private void recordTime() {
        if (timer == null) {
            timer = new Timer();
        }
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                movementTime++;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!isFinishing()) {
                            textTime.setText(String.format("%.0f.%02.0f", movementTime / 60f, (float) (movementTime % 60)));
                        }
                    }
                });
            }
        }, 0, 1000);
    }

    private void stopTime() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }
}
